<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>NodeIterator(1)</title>
</head>
<body>
  <div id="app"> Hello Div0
    <div>Hello Div1</div>
    <div>Hello Div11</div>
    <p><span></span></p>
    <h1><div>Hello Div2</div></h1>
    <p><b>Hello</b> world!</p> 
    <ul> 
      <div>Hello Div3</div>
    <li>List item 1</li> 
    <li>List item 2</li> 
    <li>List item 3</li> 
    </ul>
  </div>
</body>
<script>
   // NodeIterator的filter创建方式
   function checkNodeIterator(){
    let dom = document.querySelector('#app');
     //第一种方式(对象方式)
     let filter1 = {
      acceptNode(element){
        return element.tagName.toLowerCase() === 'p' ? NodeFilter.FILTER_ACCEPT : NodeFilter.FILTER_SKIP;
      }
     }
    //  遍历 app 下所有的元素
     let iterator1 = document.createNodeIterator(dom,NodeFilter.SHOW_ELEMENT,null,false);
     let node1 = iterator1.nextNode(); 
      while (node1 !== null) { 
        console.log(node1);
        console.log(node1.tagName);
        node1 = iterator1.nextNode(); 
      }
      // 遍历 app 下所有的 p元素
      let iterator2 = document.createNodeIterator(dom,NodeFilter.SHOW_ELEMENT,filter1,false);
      let node2 = iterator2.nextNode(); 
      while (node2 !== null) { 
        console.log(node2);
        console.log(node2.tagName);
        node2 = iterator2.nextNode(); 
      }
     //第二种方式(函数形式)
     let filter2 = function(element){
       return element.tagName.toLowerCase() === 'div' ? NodeFilter.FILTER_ACCEPT : NodeFilter.FILTER_SKIP;
     }
     // 遍历 app 下所有的 div 元素（包含 app）
     let iterator3 = document.createNodeIterator(dom,NodeFilter.SHOW_ELEMENT,filter2,false);
     let node3 = iterator3.nextNode(); 
      while (node3 !== null) { 
        console.log(node3);
        console.log(node3.tagName);
        node3 = iterator3.nextNode(); 
      }
   }
  //  checkNodeIterator();

  function checkTreeWalker(){
    // 与 nodeIterator 的区别 NodeFilter.FILTER_ACCEPT
    let dom = document.querySelector('#app');
    let filter = function(element){
      return element.tagName.toLowerCase() === 'div' ? NodeFilter.FILTER_ACCEPT : NodeFilter.FILTER_REJECT;
    };
    let iterator = document.createTreeWalker(dom,NodeFilter.SHOW_ELEMENT,filter,false);
    console.log('获取当前节点的第一个子节点',iterator.firstChild());
    console.log('获取当前节点的最后一个子节点',iterator.lastChild());
    console.log('获取当前节点的下一个同胞节点',iterator.nextSibling());
    console.log('获取当前节点的上一个同胞节点',iterator.previousNode());
    // console.log('获取当前节点的父节点',iterator.parentNode());
    console.log('上一个节点',iterator.currentNode);
    let node = iterator.nextNode();
    while(node !== null){
      console.log('当前节点',node);
      node = iterator.nextNode();
    }
  }
  // checkTreeWalker();
</script>
</html>